package adminService

import (
	//"fmt"
	"fmt"
	"gin/chibuda/app/utils"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"runtime"
	"github.com/shirou/gopsutil/cpu"
	"strconv"
	"time"
)

func SystemInit() utils.Service{
	data:=make(map[string]interface{})
	data["GOROOT"] = runtime.GOROOT()   // GO 路径
	data["GOVersion"] = runtime.Version() //GO 版本信息 go1.9
	data["GOARCH"] = runtime.GOARCH  //系统构架 386、amd64
	data["GOOS"] = runtime.GOOS  //系统版本 windows

	v, _ := mem.VirtualMemory()
	data["ramTotal"] = v.Total/(1024*1024)  //总运行内存
	data["ramUse"] = v.Used/(1024*1024)  //已使用运行内存
	value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", v.UsedPercent), 64)
	data["ramUsedPercent"] = value  //运行百分比

	res, _ := cpu.Counts(true)
	data["cpuCount"] = res   // cpu核数
	info, _ := cpu.Percent(time.Duration(time.Second), false)
	data["cpuInfo"] = info[0]   // cpu使用率

	var diskArr []interface{}
	parts, _ := disk.Partitions(true)
	for _,val:=range parts {
		diskInfo, _ := disk.Usage(val.Mountpoint)
		if diskInfo.Total == 0 || diskInfo.Total < 1024969024{
			continue
		}
		diskArr = append(diskArr,diskInfo)
	}
	data["disk"] = diskArr
	return utils.Success(data)
}

func DictGet(data map[string]string) utils.Service{
	if data["page"] == "" {
		data["page"] = "1"
	}
	if data["pageCount"] == "" {
		data["pageCount"] = "10"
	}
	query := Db().Table("admin_dict")
	if data["keyWord"] != ""{
		query.Where("name","like","%"+data["keyWord"]+"%").OrWhere("remark","like","%"+data["keyWord"]+"%")
	}
	list , _ :=query.
		Limit(utils.Int(data["pageCount"])).
		Paginate(utils.Int(data["page"]))
	return utils.Success(list)
}

func DictDel (data map[string]string) utils.Service{
	res,err:=Db().Table("admin_dict").
		Where("id",data["id"]).
		Delete()
	if err!=nil || res == 0 {
		return utils.Error("删除失败")
	}
	return utils.Success()
}

func DictuEdit(data map[string]string) utils.Service{
	if data["id"] != "" {
		res,err := Db().Table("admin_dict").
			Where("id",data["id"]).
			Data(data).
			Update()
		if err!=nil || res == 0 {
			return utils.Error(err)
		}
	}else{
		delete(data,"id")
		res,err := Db().Table("admin_dict").
			Data(data).
			Insert()
		if err!=nil || res == 0 {
			return utils.Error("添加失败")
		}
	}
	return utils.Success()
}
